<script>
import {apiCategoryList, apiGetUserById, apiProductDetail, apiProductPage} from "@/api/api";
import ProductDetail from "@/components/productDetail.vue";

  export default {
    props:{
      customStyle: {  // 新增样式prop
        type: Object,
        default: () => ({})
      },
      sellerId:{
        type : String,
        default : () => null
      },
      border:{
        type: Boolean,
        default : () => true
      },
      showPublish:{
        type: Boolean,
        default : () => true
      }
    },

    name: "ProductList",
    components: {ProductDetail},
    created() {
      this.loadCategoryList();
      this.loadProductData();
    },
    data(){
      return{
        // 价格范围（数组形式，第一个元素是最小值，第二个是最大值）
        priceRange: [0, 5000],

        // 滑块标记点
        marks: {
          100: '￥100',
          500: '￥500',
          1000: '￥1000',
          5000: '￥5000',
        },
        dialogVisible : false,
        sortV: 0,
        search: {
          categoryId : null,
          pageNum : 1,
          pageSize : 10,
          keyword : null,
          sellerId : null,
          sort : null,
          startTime : null,
          minPrice : null,
          maxPrice : null
        },
        productList:[],
        categories:[
          {id: 1, name: "分类1"},
          {id: 2, name: "分类2"},
        ],
        // 商品数量
        total : 0,
        currentDetail: null,
        userDetail: null,
        // originalProducts: [], // 保存原始顺序
      }
    },
    filters:{
      dateFormat(val){
        if (!val){
          return " "
        }else{
          return val?.split(' ')[0] // 只显示日期
        }
      }
    },
    methods:{
      async open(item) {
        this.currentDetail = null;
        this.userDetail = null;
        try {
          await this.viewDetail(item); // 等待数据加载完成
          this.dialogVisible = true;  // 再打开对话框
        } catch (error) {
          this.$message.error("加载商品详情失败");
        }
      },
      // 获取分类数据
      handlePriceChange(val) {
        // 当滑块值变化时，更新minPrice和maxPrice
        this.search.minPrice = val[0]
        this.search.maxPrice = val[1]
      },
      loadCategoryList(){
        apiCategoryList().then(res => {
          if (res.code === 200){
            this.categories = res.data;
          }else{
            this.$message.error(`商品类型列表请求失败 ${res.message}`);
          }
        });
      },
      handleSort(){
        this.sortV+=1;this.sortV%=3;
        switch (this.sortV){
          case 0: this.search.sort = null;
            // this.productList = this.originalProducts;
          break;
          case 1: this.search.sort = false;
            // this.productList = [...this.originalProducts].sort((a, b) => b.price - a.price);
            break;
          case 2: this.search.sort = true;
            // this.productList = [...this.originalProducts].sort((a, b) => a.price - b.price);
            break;
        }
        this.loadProductData();
      },
      loadProductData(){
        this.search.sellerId = this.sellerId;
        apiProductPage(this.search).then(res=>{
          if(res?.code===200){
            this.productList = res.data.records
            this.originalProducts = res.data.records
            this.total = res.data.total
          }else{
            this.$message.error(`商品数据列表请求失败 ${res.message}`)
          }
        })
      },
      getCategoryID(id){
        const c = this.categories.find(v => v.id===id).name;
        // console.log(id)
        return c?c:""
      },
      // 获取商品信息
      viewDetail(item){
        // console.log(item)
        apiGetUserById(item.userId).then(res=>{
          if (res.code===200){
            this.userDetail = res.data;
          }else{
            this.$message.error(`查询用户失败 ${res.message}`);
          }
        });
        apiProductDetail(item).then(res => {
          if (res.code === 200){
            this.currentDetail = res.data
          }else {
            this.$message.error(`获取商品详情失败 ${res.message}`)
          }
        })
      },
      // 页面大小调整
      handleSizeChange(val) {
        this.search.pageSize = val;
        // console.log(`每页 ${val} 条`);
        this.loadProductData()
      },
      // 当前页数调整
      handleCurrentChange(val) {
        this.search.pageNum = val;
        this.loadProductData()
        // console.log(`当前页: ${val}`);
      },
      handleCategory(id){
        this.search.categoryId=id;
        this.search.keyword = null;
        console.log(this.search, id);
        this.loadProductData();
      }
    }
  }
</script>

<template>
  <div class="list-bg" :style="customStyle">
    <el-backtop target=".list-bg"></el-backtop>
    <el-card class="list-card" shadow="always" :style="border?'':{border:'none'}">
      <div class="list-header">
        <div class="list-header-inner-l">
          <el-select
              v-model="search.categoryId"
              placeholder="请选择分类（可选）"
              size="large"
              style="width: 240px"
              clearable
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
              placeholder="按名查找（可选）"
              v-model="search.keyword"
              style="width: 10rem"
              clearable>
          </el-input>
          <el-date-picker
              v-model="search.startTime"
              type="datetime"
              placeholder="时间之后发布"
              value-format="yyyy-MM-dd HH:mm:ss"
          />
          <el-button type="primary" icon="el-icon-search" @click="loadProductData">搜索商品</el-button>
        </div>

        <el-button v-if="showPublish" type="primary" icon="el-icon-plus" style="float: right" @click="$router.push('/publish')">发布商品</el-button>
      </div>
      <div style="display: flex ;gap: 2rem;align-items: center">价格
          <el-slider style="min-width: 300px; width: 80%"
              v-model="priceRange"
              range
              :min="0"
              :max="5000"
              :marks="marks"
              @change="handlePriceChange"
          />
          <el-button type="primary" @click="handleSort" :icon="this.sortV!==0?this.sortV===1?'el-icon-sort-down':'el-icon-sort-up':'el-icon-sort'" size="small"/>
      </div>
      <el-row :gutter="24" class="product-grid">
        <template v-if="productList && productList.length > 0">
          <el-col v-for="item in productList" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card @click.native="open(item)"  class="product-card" shadow="always" :body-style="{ padding: '0px' }">
              <img :src="item.imageUrl" class="product-img" :alt="item.name">
              <div style="padding: 0 14px 1rem;">
                <div style="display: flex; justify-content: space-between; flex-wrap: nowrap; align-items: center">
                  <p class="text-ellipsis" style="margin: 0.5rem 0 0.5rem">{{ item.name }}</p>
                  <div style="color: #F56C6C">￥{{ item.price }}</div>
                </div>
                <div class="clearfix">
                  <span class="time">{{ item.createTime | dateFormat }}</span>
                  <span  class="ID hover-underline" @click.stop="handleCategory(item.categoryId)">{{ getCategoryID(item.categoryId) }}</span>
                  <el-button type="text" class="button hover-underline" style="padding: 0" @click.stop="open(item)">
                    商品详情
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </template>
        <template v-else>
          <el-col :span="24">
            <h3 style="text-align: center; margin: 8rem 0">没有符合条件的商品</h3>
          </el-col>
        </template>
      </el-row>
      <div style="display: flex; align-items: center;justify-content: center;padding-top: 1rem">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="search.pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="search.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog fullscreen destroy-on-close center :visible.sync="dialogVisible" title="商品详情（点击查看大图）"
               custom-class="custom-dialog">
<!--      <span>商品详情</span>-->
      <template style="padding: 0">
        <product-detail v-if="dialogVisible && currentDetail"
                            :current-detail="currentDetail" :user-detail="userDetail"/>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.text-ellipsis {
  white-space: nowrap;      /* 禁止换行 */
  overflow: hidden;         /* 隐藏溢出 */
  text-overflow: ellipsis;  /* 显示省略号 */
  width: 10rem;            /* 必须指定宽度 */
}
.el-dialog, .el-dialog--center {
  min-width: 400px !important;
}
.el-dialog__body{
  padding: 0 !important;
}
.product-detail-dialog{
  overflow: auto !important;
  box-sizing: border-box;
  //width: 300px;       /* 包含内容+内边距+边框 */
  padding: 20px;
  border: 5px solid;
  height: 100vh - 2rem !important;
}

.product-card {
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64,158,255,0.1);
  padding: 32px 24px 16px 24px;
  width: auto;
  height: auto;
}
.list-bg {
  height: 100%;
  background: url("@/assets/bg/bg.png") center;
  background-size: cover;
  padding: 32px 1rem 1rem;
  margin: 0 0 0;
  overflow: auto;
}
.list-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64,158,255,0.08);
  padding: 24px;
}
.detail-img {
  width: 100%;
  max-height: 70vh;
  border-radius: 12px;
  object-fit: cover;
  border: 1px solid #eee;
}
.list-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 1rem;
  justify-content: space-between;
  flex-wrap: wrap;
}
.list-header-inner-l {
  flex-wrap: wrap;
  display: flex;
  gap: 1rem;
}
.clearfix{
  color: gray;
  font-size: 0.8rem;
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  align-items: center;
}
.product-grid {
  margin-top: 8px;
}
.product-col {
  margin-bottom: 24px;
}
.product-card {
  padding: 0;
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease; /* 平滑过渡效果 */
  margin-top: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 默认阴影 */
}

.product-card:hover {
  box-shadow: 0 2px 8px #409EFF; /* 悬浮时蓝色阴影 */
  transform: scale(1.02); /* 稍微放大 */
}

.product-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  //border-radius: 8px 8px 0 0;
  //margin-bottom: 12px;
  background: #f5f7fa;
}
.product-info {
  width: 100%;
  padding: 0 8px 8px 8px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.product-name {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
.product-price {
  color: #ff4073;
  font-size: 1.1rem;
  margin-bottom: 4px;
}
.product-meta {
  font-size: 12px;
  color: #888;
  margin-bottom: 8px;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.product-category {
  background: #e3f0ff;
  color: #409EFF;
  border-radius: 4px;
  padding: 0 6px;
  margin-right: 8px;
}
</style>